package com.xdk.templatescala.utils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * 反射工具类
 *
 * @author: cwl
 * @date: 2020-10-17
 */
public class ReflectUtils {

    private static final String EMPTY_STRING = "";

    /**
     * 把object中数据转换成map
     *
     * @param object
     * @return
     */
    public static Map<String, Object> toMap(Object object) throws IllegalAccessException {
        if (object == null) {
            return null;
        }
        Map<String, Object> result = new HashMap<>();

        Class objClass = object.getClass();
        Field[] fields = objClass.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            result.put(field.getName(), field.get(object));
        }

        return result;
    }

    /**
     * 把object中数据转换成map
     *
     * @param object
     * @return
     */
    public static Map<String, String> toStringMap(Object object) throws IllegalAccessException {
        if (object == null) {
            return null;
        }
        Map<String, String> result = new HashMap<>();

        Class objClass = object.getClass();
        Field[] fields = objClass.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            if(null == field.get(object)){
                result.put(field.getName(), EMPTY_STRING);
            }else{
                result.put(field.getName(), String.valueOf(field.get(object)));
            }

        }

        return result;
    }
    public static void main(String[] args) {

    }
}